/**
 * 部门js
 */
var transaction = {
	curPage : 1,
	pageSize : 10,
	dataCache : null,

    startEvent: function () {
        // 按回车键登录事件
        document.onkeydown = function (e) {
            var ev = document.all ? window.event : e;
            if (ev.keyCode == 13) {
                transaction.curPage = 1;
                transaction.setPageChange(null);
                transaction.search();
            }
        };
    },

    getChannelResource : function() {
        var url = 'mgr/order/getUserList';
        var params = {
            'userId':userId
        };
        var cb = function(data) {
            if (data.resultCode == 200) {
                var option = '<option value="">请选择</option>';
                for (var i = 0; i < data.result.length; i++) {
                    var singleObj = data.result[i];
                    option = option + '<option value="' + singleObj.channelId + '">'
                        + singleObj.name + '</option>';
                }
                $('select[name="channel"]').append(option);
            }
        };
        sendApiNoLoad(url ,params, cb, 'POST');
    },

	getResource : function() {
		var url = 'mgr/ProductInfoCtrl/getProductInfoList';
		var params = {
			'curPage' : 1,
			'pageSize' : 9999,
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择产品名称</option>';
				option = option + '<option value=1>公募基金</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
							+ singleObj.name + '</option>';
				}
				$('select[name="productId"]').append(option);
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},

	bindEvent : function() {
		// 查询
		$('#searchData').click(function() {
			transaction.curPage = 1;
			transaction.setPageChange(null);
			transaction.search();
		});

		$('#addData').on('click', function() {
			var path = APP_ADDRESS + 'mgr/trade/transactionAdd.jsp';
			art.dialog.open(path, {
				title : '添加订单',
				width : 380,
				height : 100,
				ok : function() {
					var returnStatus = this.iframe.contentWindow.submitForm();
					if (returnStatus) {
						transaction.setPageChange(null);
						transaction.search();
					}
					return false;
				},
				cancel : true
			});
		});
		$('#excel').on('click', function() {
			var url = '../../../mgr/order/excel';
			if (typeof (pageIdx) != "undefined") {
				transaction.curPage = pageIdx;
			}

			var id = $.trim($('#searchModForm input[name="id"]').val());
			var userName = $.trim($('#searchModForm input[name="userName"]').val());
			var productId = $.trim($('#productId').val());
			var beginDate = $.trim($('#beginDate').val());
			var endDate = $.trim($('#endDate').val());
			var financialName = $.trim($('#searchModForm input[name="financialName"]').val());
			var payStatus = $.trim($('#searchModForm select[name="payStatus"]').val());
			var company = $.trim($('#company').val());
			var contractTitle = $.trim($('#searchModForm input[name="contractTitle"]').val());
            var channel = $('select[name="channel"]').val();
            var orgId = $.trim($('#orgId').val());

			location.href = url+"?id="+ id + "&userName=" + userName + "&productId=" + productId
							+"&beginDateStr=" + beginDate + "&endDateStr=" + endDate
							+"&userId=" + userId + "&payStatus=" + payStatus+"&company="+company+"&financialName="
							+financialName+"&contractTitle="+contractTitle+"&channel="+channel+"&orgId="+orgId;
		});
		$('#order_123').on('click',function(){

			var aa = $('.checkItem');
			var ss = [];
			for (var i = 0; i < aa.length; i++) {
				if (aa[i].checked) {
					ss.push( aa[i].value);
				}
			}

			if(ss.length == 0){
				alert("请至少选择一笔订单！");
				return false;
			}
			art.dialog.data('selectedOrders', ss);

			var path=APP_ADDRESS+'mgr/transaction/order/orderMutiUpdateCode.jsp';
			art.dialog.open(path, {
				title: '批量订单修改推荐码',
				width: 500,
				height:580,
				ok: function () {
					returnStatus=this.iframe.contentWindow.submitForm();
					if(returnStatus == true){
						transaction.setPageChange(transaction.curPage);
						transaction.search(transaction.curPage);
					}
					return returnStatus;
				},
				cancel: true
			});
		});
		$('#checkAll').unbind();
		$('#checkAll').on('click',function(){
			if($("#checkAll").prop("checked")){
				$(".checkItem").prop("checked", 'true');
			}else{
				$(".checkItem").removeAttr("checked");
			}

		});

		$("select[name='pageSize']").change(function() {
			transaction.pageSize = $('#pageSize').val();
			transaction.setPageChange(transaction.curPage);
		});

	},
	reSize: function () {
	//从新设置ifrma 大小
		console.log($("#orderBox"));
		var height = $("#orderBox").height();
		console.log("box height = " + $("#orderBox").height());

		//console.log($("#order"));

		//console.log("orderBody height = " + document.getElementById("order").offsetHeight);

		$("#order").css("height", height);
	},

	// 设置分页
	setPageChange : function(delCurPage) {
		 var begin_date = $.trim($('#begin_date').val());
	     var end_date = $.trim($('#end_date').val());

		var url = 'mgr/order/list';

		if (typeof (pageIdx) != "undefined") {
			transaction.curPage = pageIdx;
		}

		var params = jsUtils.serializeJson($('#searchModForm'));
		params.curPage = 1;
		params.pageSize = 999999;
		params.userId = userId;

		var cb = function(data) {
			if (data.resultCode == 200) {
				var totalCount = data.size;
				var pageTotal = (totalCount / transaction.pageSize > 0) ? Math
						.ceil(totalCount / transaction.pageSize) : 1;

				pageHelper.init(pageTotal, totalCount, transaction.search,
						delCurPage); // 翻页事件
			}else{
				alert(data.msg);
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},

	// 查询交易记录
	search : function(pageIdx) {
		var url = 'mgr/order/list';
		if (typeof (pageIdx) != "undefined") {
			transaction.curPage = pageIdx;
		}

		var params = jsUtils.serializeJson($('#searchModForm'));
		params.curPage = transaction.curPage;
		params.pageSize = transaction.pageSize;
		params.userId = userId;


		var cb = function(data) {
			$('#tableList tbody').empty();
			var tr = '';

			if (data.result != null && data.result.length > 0) {
				for (var i = 0; i < data.result.length; i++) {

					var singleObj = data.result[i];

					var key = singleObj.col01id + "_Order_Key";

					localStorage.setItem(singleObj.col01id + "_Order_Key", JSON.stringify(singleObj));

					tr += '<tr class="row"><td class="col-md-1"><input type="hidden" name="id" value="' +singleObj.col01id+'"/>'
							+ '<input type="hidden" name="channel" value="'+ singleObj.col26channel + '"/>'
							+ '<input type="hidden" name="recommendCode" value="' + singleObj.col24insidePhoneNum +'"/>'
							+ '<input type="hidden" name="contractUrl" value="' + singleObj.col32contractUrlPDf +'"/>'
							+ '<input type="hidden" name="contractTitle" value="' + singleObj.col31contractTitle +'"/>'
						    + '<input type="hidden" name="col36contractUrlPDF1" value="' + singleObj.col36contractUrlPDF1 +'"/>'
						    + '<input type="hidden" name="col36contractTitle1" value="' + singleObj.col36contractTitle1 +'"/>'
						    + '<input type="hidden" name="col36contractUrlPDF2" value="' + singleObj.col36contractUrlPDF2 +'"/>'
						    + '<input type="hidden" name="col36contractTitle2" value="' + singleObj.col36contractTitle2 +'"/>'
						    + '<input type="hidden" name="col36contractUrlPDF3" value="' + singleObj.col36contractUrlPDF3 +'"/>'
						    + '<input type="hidden" name="col36contractTitle3" value="' + singleObj.col36contractTitle3 +'"/>'
							+ '<input type="hidden" name="col36contractUrlPDF4" value="' + singleObj.col36contractUrlPDF4 +'"/>'
							+ '<input type="hidden" name="col36contractTitle4" value="' + singleObj.col36contractTitle4 +'"/>'
							+ '<input type="hidden" name="col36contractUrlPDF5" value="' + singleObj.col36contractUrlPDF5 +'"/>'
							+ '<input type="hidden" name="col36contractTitle5" value="' + singleObj.col36contractTitle5 +'"/>'
							+ '<input type="hidden" name="col34confirmationPdf" value="' + singleObj.col34confirmationPdf +'"/>'
							+ '<input type="hidden" name="col36contractTitle3" value="' + singleObj.col36contractTitle +'"/>'
							+ '<input type="hidden" name="col34confirmationPdf" value="' + singleObj.col34confirmationPdf +'"/>'
							+ '<input type="hidden" name="col36contractTitle3" value="' + singleObj.col36contractTitle3 +'"/>'
							+ '<input type="hidden" name="col34confirmationPdf" value="' + singleObj.col34confirmationPdf +'"/>'
							+ '<input type="hidden" name="kycUrl" value="' + singleObj.kycUrl +'"/>'
							+ '<input type="checkbox" name ="checkItem" class="checkItem" value="' + singleObj.col01id + '"  style="margin-right: 10px;"/>'
							+ (i + 1)
							+ '</td><td class="col-md-1">'
							+ singleObj.col01id
							+ '</td><td class="col-md-1">'
							+ (singleObj.col21userName != null ?singleObj.col21userName:"")
							+ '</td><td class="col-md-1">'
							+ (singleObj.col22userPhoneNum != null? singleObj.col22userPhoneNum:"")
							+ '</td><td class="col-md-1">'
							+ singleObj.col02amount
							+ '</td><td class="col-md-1">'
							+ (singleObj.col03niggerAmount !=null ? singleObj.col03niggerAmount:"")
							+ '</td><td class="col-md-1">'
							+ singleObj.col04status
							+ '</td><td class="col-md-1">'
							+ singleObj.col10productName
							+ '</td><td class="col-md-1">'
							+ (singleObj.col23insideName != null?singleObj.col23insideName:"")
							+ '</td><td class="col-md-1">'
							+ singleObj.col51cts
							+ '</td><td class="col-md-1">'
							+ (singleObj.col28orgName != null?singleObj.col28orgName:"")
							+ '</td><td class="col-md-1">'
							+'<a type="button" name="order_99" class="btn btn-primary btn-xs lookData" style="margin-left: 5px; margin-top: 10px; display:none;">'
							+'<i class="fa fa-search"></i>查看</a>'
							+'<a type="button" name="order_113" class="btn btn-primary btn-xs lookContract" style="margin-left: 5px; margin-top: 10px; display:none;">'
							+'<i class="fa fa-search"></i>查看合同</a>'
							+'<a type="button" name="order_114" class="btn btn-primary btn-xs lookTZQRH" style="margin-left: 5px; margin-top: 10px; display:none;">'
							+'<i class="fa fa-search"></i>查看投资确认函</a>'
							+'<a type="button" name="order_103" class="btn btn-primary btn-xs updOrderCode" style="margin-left: 5px; margin-top: 10px; display:none;">'
							+'<i class="fa fa-edit"></i> 修改推荐码/渠道</a>'
							+'<a type="button" name="order_125" class="btn btn-primary btn-xs kycUrl" style="margin-left: 5px; margin-top: 10px; display:none;">'
							+'<i class="fa fa-edit"></i> 风险测评</a>'
							+'</td></tr>';
				}



			} else {
				tr = '<tr><td colspan="6" style="text-align: center;color: red;">暂无数据</td></tr>';
			}
			$('#tableList tbody').html(tr);
			transaction.bindEventOtherBtn();
			jsUtils.controlFunctionBtn();
			transaction.reSize();
		};

		sendApiNoLoad(url, params, cb, 'POST');
	},

	bindEventOtherBtn : function() {
		$('.deleteData').unbind();
		$('.deleteData').on(
				'click',
				function() {
					var thisObj = $(this);
					art.dialog.confirm('你确认删除？', function() {
						var id = thisObj.parent().parent().find(
								'input[name="id"]').eq(0).val();
						var url = 'mgr/transactionCtrl/deletetransaction';
						var params = {
							'id' : id
						};
						var cb = function(data) {
							alert('删除成功！');
							transaction.setPageChange(transaction.curPage);
							transaction.search(transaction.curPage);
						}
						sendApiNoLoad(url, params, cb, 'POST');
					}, function() {
					});
				});
		$('.lookContract').unbind();
		$('.lookContract').on('click', function() {
			var thisObj = $(this);

			var url1 = thisObj.parent().parent().find('input[name="contractUrl"]').eq(0).val();
			var title1 = thisObj.parent().parent().find('input[name="contractTitle"]').eq(0).val();

			if(url1 == null || url1 == ''){
				var orderId = thisObj.parent().parent().find('input[name="id"]').eq(0).val();
				var url = 'mgr/order/createContract?orderId=' + orderId;
				var cb = function (data) {
					layer.msg(data.msg, {icon: 1});
					layer.close(index);
					this.refashData();
				};
				var index = layer.load(0, {shade: false});

				sendApiNoLoad(url, null, cb, 'GET');
			}

			var url2 = thisObj.parent().parent().find('input[name="col36contractUrlPDF1"]').eq(0).val();
			var title2 = thisObj.parent().parent().find('input[name="col36contractTitle1"]').eq(0).val();

			var url3 = thisObj.parent().parent().find('input[name="col36contractUrlPDF2"]').eq(0).val();
			var title3 = thisObj.parent().parent().find('input[name="col36contractTitle2"]').eq(0).val();

			var url4 = thisObj.parent().parent().find('input[name="col36contractUrlPDF3"]').eq(0).val();
			var title4 = thisObj.parent().parent().find('input[name="col36contractTitle3"]').eq(0).val();

			var url5 = thisObj.parent().parent().find('input[name="col36contractUrlPDF4"]').eq(0).val();
			var title5 = thisObj.parent().parent().find('input[name="col36contractTitle4"]').eq(0).val();

			var url6 = thisObj.parent().parent().find('input[name="col36contractUrlPDF5"]').eq(0).val();
			var title6 = thisObj.parent().parent().find('input[name="col36contractTitle5"]').eq(0).val();

			var path = APP_ADDRESS+'mgr/transaction/order/sysOrderContract.jsp';

			art.dialog.data('url1', url1);
			art.dialog.data('title1', title1);

			art.dialog.data('url2', url2);
			art.dialog.data('title2', title2);

			art.dialog.data('url3', url3);
			art.dialog.data('title3', title3);

			art.dialog.data('url4', url4);
			art.dialog.data('title4', title4);

			art.dialog.data('url5', url5);
			art.dialog.data('title5', title5);

			art.dialog.data('url6', url6);
			art.dialog.data('title6', title6);

			var dialog = art.dialog.open(path, {
				title: '查看合同',
				width:  600,
				height: 250,
				ok: true
			});


		});
		$('.lookData').unbind();
		$('.lookData').on(
				'click',
				function() {
					var thisObj = $(this);
					var id = thisObj.parent().parent().find('input[name="id"]')
							.eq(0).val();
					art.dialog.data('lokId', id);
					var path = APP_ADDRESS
							+ 'mgr/transaction/order/orderLook.jsp';
					art.dialog.open(path, {
						title : '查看订单详情',
						width : 600,
						height : 700,
						cancel : true
					});
				});
        $('.lookData').unbind();
        $('.lookData').on(
            'click',
            function () {
                var thisObj = $(this);
                var id = thisObj.parent().parent().find('input[name="id"]')
                    .eq(0).val();
                art.dialog.data('lokId', id);
                var path = APP_ADDRESS
                    + 'mgr/transaction/order/orderLook.jsp';
                art.dialog.open(path, {
                    title: '查看订单详情',
                    width: 600,
                    height: 700,
                    cancel: true
                });
            });

        $('.lookTZQRH').unbind();
        $('.lookTZQRH').on('click', function () {
            var thisObj = $(this);
            var url = thisObj.parent().parent().find('input[name="col34confirmationPdf"]').eq(0).val();

            if (url != null && url != '' && url != "null") {
                window.open(url);
            } else {
                var orderId = thisObj.parent().parent().find('input[name="id"]').eq(0).val();
                var url = 'mgr/order/createTZQRH?orderId=' + orderId;
                var cb = function (data) {
                    layer.msg(data.msg, {icon: 1});
                    layer.close(index);
                    this.refashData();
                };
                var index = layer.load(0, {shade: false});

                sendApiNoLoad(url, null, cb, 'GET');
            }

        });

		$('.kycUrl').unbind();
		$('.kycUrl').on('click', function() {
			var thisObj = $(this);
			var url = thisObj.parent().parent().find('input[name="kycUrl"]').eq(0).val();

			if(url != null && url != '' && url !="null"){
				window.open(url);
			}else{
				alert("该用户未做测评");
				var orderId = thisObj.parent().parent().find('input[name="id"]').eq(0).val();
				var url = 'mgr/order/createKYCDoc?orderId=' + orderId;
				var cb = function (data) {
					layer.msg(data.msg, {icon: 1});
					layer.close(index);
					this.refashData();
				};
				var index = layer.load(0, {shade: false});

				sendApiNoLoad(url, null, cb, 'GET');
			}
		});

		$('.updOrderCode').unbind();
		$('.updOrderCode').on('click',function(){
			var thisObj=$(this);
			var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
			var channel=thisObj.parent().parent().find('input[name="channel"]').eq(0).val();
			var recommendCode=thisObj.parent().parent().find('input[name="recommendCode"]').eq(0).val();
			art.dialog.data('updId', id);
			art.dialog.data('channel', channel);
			art.dialog.data('recommendCode', recommendCode);
			var path=APP_ADDRESS+'mgr/transaction/order/orderUpdateCode.jsp';
			var returnStatus = false;
			var dialog = art.dialog.open(path, {
				title: '修改订单推荐码和渠道',
				width: 500,
				height:150,
				ok: function () {
					var returnStatus=this.iframe.contentWindow.submitForm();
					if(returnStatus){
						//alert("returnStatus = " + returnStatus );
						dialog.close();
						transaction.setPageChange(transaction.curPage);
						transaction.search(transaction.curPage);
					}
					return false;
				},
				cancel: true
			});
		});
	},

	init : function() {

        // set default search date as today
        var today = $.datepicker.formatDate('yy-mm-dd', new Date());

        $('#beginDate').val(today);
        $('#endDate').val(today);
        //console.log($('#beginDate').val()+' '+$('#endDate').val()) ;

		jsUtils.controlFunctionBtn();
		transaction.getResource();
		transaction.setPageChange(null);
		transaction.search();
		transaction.startEvent();
		transaction.bindEvent();
		transaction.getChannelResource();

	}
};

$(document).ready(function() {
	transaction.init();
});

//提供给外部刷新调用
function refashData() {
	transaction.setPageChange(null);
	transaction.search();
}

//渠道改变
function changeChannel () {
    var channelVal = $('select[name="channel"]').val();
    var channelUrl = 'mgr/order/getOrg?channelId=' + channelVal;

    $('select[name="orgId"]').empty();

    var cb = function(data) {
        console.dir(data);
        if (data.resultCode == 200) {
            var option = '<option value="">请选择</option>';
            for (var i = 0; i < data.result.length; i++) {
                var singleObj = data.result[i];
                option = option + '<option value="' + singleObj.orgId + '">'
                    + singleObj.orgName + '</option>';
            }
            $('select[name="orgId"]').append(option);
        }
        else {
            alert('该渠道还没有分公司');
        }

    };
    sendApiNoLoad(channelUrl, null, cb, 'GET');


}


function changeFrameHeight(name){
	var ifm= document.getElementById(name);
	ifm.height= 1200;
	//var subWeb = document.frames ? document.frames[name].document : ifm.contentDocument;
	//if(ifm != null && subWeb != null) {
	//	console.log("subWeb.body.scrollHeight = " + subWeb.body.scrollHeight);
	//	ifm.height = subWeb.body.scrollHeight;
	//}


	//console.log(name);
	//console.log("id = " + name)
	//console.log("will change hight name = " + name);
	//var ifm= document.getElementById(name);
	//
	//console.log($(ifm).contents().find(".box"));
	//console.log("body hight = " + $(ifm).contents().find(".box").height());
	//
	//
	//var box = ifm.getElementsByClassName("box");
	//console.log(box);
	//console.log("height01 = " + ifm.clientHeight); //  name.document.documentElement.clientHeight);
	//
	//console.log("height02 = " + ifm.scrollHeight);
	//
	//console.log("height = " +  height);
	////if(height < 925){
	////	height = 925;
	////}
	//
	//ifm.height= ifm.body.scrollHeight;

}


